package com.digitalchina.lxnsy.activity.old;

import android.app.DatePickerDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import androidx.annotation.NonNull;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.digitalchina.lxnsy.R;
import com.digitalchina.lxnsy.api.BusinessFile;
import com.digitalchina.lxnsy.api.BusinessPlan;
import com.digitalchina.lxnsy.base.BaseActivity;
import com.digitalchina.lxnsy.constant.MSG;
import com.digitalchina.lxnsy.entity.AddFarmAccVO;
import com.digitalchina.lxnsy.entity.FarmAccountsVO;
import com.digitalchina.lxnsy.entity.FileVO;
import com.digitalchina.lxnsy.loader.GlideImageLoader;
import com.digitalchina.lxnsy.toolkit.DateStyle;
import com.digitalchina.lxnsy.toolkit.DateUtil;
import com.digitalchina.lxnsy.toolkit.FastJsonUtil;
import com.digitalchina.lxnsy.toolkit.FrescoUtil;
import com.digitalchina.lxnsy.toolkit.StringUtil;
import com.facebook.drawee.view.SimpleDraweeView;
import com.lzy.imagepicker.ImagePicker;
import com.lzy.imagepicker.bean.ImageItem;
import com.lzy.imagepicker.ui.ImageGridActivity;

import java.util.ArrayList;
import java.util.Calendar;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * ================================================
 * 项目名称：BigData
 * 类描述：
 * 包名：com.digitalchina.bigdata.activity
 * 创建人：郑皓
 * 创建时间：2018/8/30 19:13
 * 修改备注：
 * ================================================
 */
public class AddFarmAccountActivity extends BaseActivity {


    @Bind(R.id.iv_img)
    ImageView ivImg;
    @Bind(R.id.tv_name)
    TextView tvName;
    @Bind(R.id.et_money)
    EditText etMoney;
    @Bind(R.id.tv_time)
    TextView tvTime;
    @Bind(R.id.layout_time)
    RelativeLayout layoutTime;
    @Bind(R.id.sdv_img0)
    SimpleDraweeView sdvImg0;
    @Bind(R.id.sdv_img1)
    SimpleDraweeView sdvImg1;
    @Bind(R.id.sdv_img2)
    SimpleDraweeView sdvImg2;
    @Bind(R.id.sdv_img3)
    SimpleDraweeView sdvImg3;
    @Bind(R.id.et_remark)
    EditText etRemark;
    @Bind(R.id.bt_save)
    Button btSave;

    private int mYear, mMonth, mDayOfMonth;//播种时间  年月日
    // 图片
    public static final int IMAGE_ITEM_ADD = -1;
    public static final int REQUEST_CODE_SELECT = 100;
    private ImagePicker imagePicker;
    private String[] imgs = {"", "", "", ""};
    private SimpleDraweeView[] sdvArray = new SimpleDraweeView[4];
    private int select = 0;

    private String id = "";
    private String type = "";
    private String productPlanId = "";
    private String typeCode = "";

    Uri uri = Uri.parse("res://com.digitalchina.bigdata/" + R.drawable.selector_image_add);

    @Override
    public void setLayout() {
        setContentLayout(R.layout.activity_add_farm_account);
        setTitle("新增记账");
    }

    @Override
    public void initMember() {

        sdvArray[0] = sdvImg0;
        sdvArray[1] = sdvImg1;
        sdvArray[2] = sdvImg2;
        sdvArray[3] = sdvImg3;

        //打开选择,本次允许选择的数量
        imagePicker = ImagePicker.getInstance();
        imagePicker.setImageLoader(new GlideImageLoader());   //设置图片加载器
        imagePicker.setShowCamera(true);  //显示拍照按钮
        imagePicker.setCrop(false);        //允许裁剪（单选才有效）
        imagePicker.setMultiMode(false);    //是否多选模式


        if (getIntent().hasExtra("AddFarmAccVO")) {
            AddFarmAccVO addFarmAccVO = (AddFarmAccVO) getIntent().getSerializableExtra("AddFarmAccVO");

            ivImg.setImageResource(addFarmAccVO.getImage());
            tvName.setText(addFarmAccVO.getName());

            id = addFarmAccVO.getId();
            type = addFarmAccVO.getType();
            productPlanId = addFarmAccVO.getProductPlanId();
            typeCode = addFarmAccVO.getAccountTypeCode();
        } else {
            FarmAccountsVO vo = (FarmAccountsVO) getIntent().getSerializableExtra("FarmAccountsVO");
            id = vo.getId();
            type = vo.getType() + "";
            productPlanId = vo.getProductPlanId();
            typeCode = vo.getAccountType().getCode();

            ivImg.setImageResource(vo.getImg() != 0 ? vo.getImg() : R.drawable.ic_farm_account_out_1);
            tvName.setText(vo.getAccountType().getName());
            etMoney.setText(vo.getMoney() + "");
            etRemark.setText(vo.getRemark());
            tvTime.setText(DateUtil.StringToString(vo.getAccountDate(), DateStyle.YYYY_MM_DD));

            if (vo.getFarmAccountDescImageList() != null && vo.getFarmAccountDescImageList().size() > 0) {
                for (int i = 0; i < vo.getFarmAccountDescImageList().size(); i++) {
                    imgs[i] = vo.getFarmAccountDescImageList().get(i).getImage();
                    FrescoUtil.showImageSmall(imgs[i], sdvArray[i]);
                }
            }
        }

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == ImagePicker.RESULT_CODE_ITEMS) {
            //添加图片返回
            if (data != null && requestCode == REQUEST_CODE_SELECT) {
                ArrayList<ImageItem> images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
                if (images != null && images.size() > 0) {
                    showDialog("正在上传图片...");
                    BusinessFile.imageCompressAndUpload(this, images.get(0).path, mHandler);
                }

            }
        }
    }

    @Override
    public void addListener() {

    }

    @Override
    public void setHandler() {
        mHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);

                switch (msg.what) {
                    case MSG.MSG_SAVE_FARM_ACCOUNT_SUCCESS:
                        showToast("保存成功");
                        setResult(RESULT_OK);
                        finish();
                        break;
                    case MSG.MSG_SAVE_FARM_ACCOUNT_FIELD:
                        showToast(msg.obj.toString());
                        break;
                    case MSG.MSG_FILE_UPLOAD_SUCCESS: // 上传图片
                        dismissDialog();
                        FileVO fileVO = FastJsonUtil.getBean(msg.obj.toString(), "fileStorage", FileVO.class);
                        if (fileVO != null) {
                            imgs[select] = fileVO.getName();
                            setImageView(fileVO.getName());
                        }
                        break;
                    case MSG.MSG_FILE_UPLOAD_FIELD:
                        dismissDialog();
                        showToast(msg.obj.toString() + "");
                        break;
                }
            }
        };
    }

    private void setImageView(String fileName) {
        FrescoUtil.showImageSmall(fileName, sdvArray[select]);
    }

    @Override
    public void callBack(Object object) {

    }

    @Override
    public void rightOnClick() {

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    @OnClick({R.id.layout_time, R.id.sdv_img0, R.id.sdv_img1, R.id.sdv_img2, R.id.sdv_img3, R.id.bt_save})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.layout_time:
                showDatePicker();
                break;
            case R.id.sdv_img0:
                selectImage(0);
                break;
            case R.id.sdv_img1:
                selectImage(1);
                break;
            case R.id.sdv_img2:
                selectImage(2);
                break;
            case R.id.sdv_img3:
                selectImage(3);
                break;
            case R.id.bt_save:
                save();
                break;
        }
    }

    // 选择图片
    private void selectImage(int i) {
        select = i;
        if (StringUtil.isStrEmpty(imgs[select])) {
            Intent intent = new Intent(AddFarmAccountActivity.this, ImageGridActivity.class);
            startActivityForResult(intent, REQUEST_CODE_SELECT);
        } else {
            new MaterialDialog.Builder(AddFarmAccountActivity.this)
                    .title("提示")
                    .content("是否删除这张照片？")
                    .positiveText("删除")
                    .negativeText("取消")
                    .onPositive(new MaterialDialog.SingleButtonCallback() {
                        @Override
                        public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                            imgs[select] = "";
                            sdvArray[select].setImageURI(uri);
                        }
                    })
                    .show();
        }

    }

    /**
     * 提交表单
     */
    private void save() {

        if (StringUtil.isTextEmpty(tvTime)) {
            showToast("请选择账单日期");
            return;
        }

        if (StringUtil.isEditEmpty(etMoney)) {
            showToast("请输入金额");
            return;
        }


        BusinessPlan.saveFarmAccount(this, id, type, productPlanId,
                typeCode, tvTime.getText().toString(), etMoney.getText().toString(),
                etRemark.getText().toString(), getImages(), mHandler);
    }

    public String getImages() {

        String s = "";
        for (String img : imgs) {
            if (!StringUtil.isStrEmpty(img))
                s += img + ",";
        }

        if (!StringUtil.isStrEmpty(s))
            s = s.substring(0, s.length() - 1);

        return s;
    }

    /**
     * 显示日期选择
     */
    private void showDatePicker() {

        Calendar calendar = Calendar.getInstance();
        mYear = calendar.get(Calendar.YEAR);
        mMonth = calendar.get(Calendar.MONTH);
        mDayOfMonth = calendar.get(Calendar.DAY_OF_MONTH);

        DatePickerDialog datePickerDialog = new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() {
            @Override
            public void onDateSet(DatePicker datePicker, int year, int month, int dayOfMonth) {
                String selectDate = year + "-" + (month + 1) + "-" + dayOfMonth;
                tvTime.setText(selectDate);
            }
        }, mYear, mMonth, mDayOfMonth);

//        datePickerDialog.getDatePicker().setMaxDate(System.currentTimeMillis() - 1000);
        datePickerDialog.show();
    }
}
